package com.bjlytr.license.client.core;

import com.bjlytr.license.client.entity.CustomKeyStoreParam;
import com.bjlytr.license.client.entity.LicenseVerifyParam;
import de.schlichtherle.license.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * @author Ledison
 * @date 2021/9/16
 */
@Slf4j
public class LicenseVerify {

    /**
     * 安装License证书
     */
    public synchronized LicenseContent install(LicenseVerifyParam param) {
        LicenseContent result = null;
        //1. 安装证书
        try {
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();
            result = licenseManager.install(new File(param.getLicensePath()));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            log.info(String.format("证书安装成功，证书有效期：%s - %s", simpleDateFormat.format(result.getNotBefore()), simpleDateFormat.format(result.getNotAfter())));
        } catch (Exception e) {
            log.error("证书安装失败！" + e.getMessage());
            try {
                Thread.sleep(5000);
            } catch (Exception se) {
                se.printStackTrace();
            }
            System.exit(0);
        }
        return result;
    }

    /**
     * 校验License证书
     */
    public boolean verify() {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        //2. 校验证书
        try {
            LicenseContent licenseContent = licenseManager.verify();
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            log.info("证书校验通过，证书有效期：{} - {}",
//                    simpleDateFormat.format(licenseContent.getNotBefore()),
//                    simpleDateFormat.format(licenseContent.getNotAfter()));
            return true;
        } catch (Exception e) {
            log.error("证书校验失败！", e);
            return false;
        }
    }

    /**
     * 初始化证书生成参数
     */
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);
        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());
        KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
                , param.getPublicKeysStorePath()
                , param.getPublicAlias()
                , param.getStorePass()
                , null);
        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , publicStoreParam
                , cipherParam);
    }

}
